# coding=utf-8
import tornado.web

import WrapCursor
from CommonLib import *
from database.models.ControllerPoint import ControllerPoint
from database.models.DatabaseCommon import *


class NameNewControlPointsHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            a = ojson['id']
            a = ojson['name']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error:' + str(e.message)))
            return
        engine = create_engine('sqlite:///ai-ele.db', echo=False)
        Session = sessionmaker(bind=engine)
        session = Session()
        cplen = session.query(ControllerPoint).filter_by(id=ojson['id']).count()
        if cplen != 1:
            self.write(r.Error('id error'))
            return
        # check name
 
        namelen = session.query(ControllerPoint).filter_by(name=ojson['name']).count()
        if namelen != 0:
            self.write(r.Error('already has this name'))
            return
        cp = session.query(ControllerPoint).filter_by(id=ojson['id']).one()
        cp.name=ojson['name']
        session.commit()
        self.write(r.Ok('name new control points successful'))
